<template>
  <div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>工单管理</span>
          <el-button type="primary" @click="handleAdd">创建工单</el-button>
        </div>
      </template>
      
      <el-table :data="workOrderList" style="width: 100%">
        <el-table-column prop="workOrderNo" label="工单号" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="planQuantity" label="计划数量" />
        <el-table-column prop="actualQuantity" label="实际数量" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="text" @click="handleStart(row)" v-if="row.status === 'pending'">开始</el-button>
            <el-button type="text" @click="handleComplete(row)" v-if="row.status === 'running'">完成</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getWorkOrderList, startWorkOrder, completeWorkOrder } from '@/utils/api'
import { ElMessage } from 'element-plus'

const workOrderList = ref([])

const loadData = async () => {
  try {
    const res = await getWorkOrderList()
    workOrderList.value = res.data
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const getStatusType = (status) => {
  const map = {
    pending: 'info',
    running: 'primary',
    completed: 'success',
    stopped: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    pending: '待生产',
    running: '生产中',
    completed: '已完成',
    stopped: '已停止'
  }
  return map[status] || status
}

const handleStart = async (row) => {
  try {
    await startWorkOrder(row.id)
    ElMessage.success('工单开始成功')
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleComplete = async (row) => {
  try {
    await completeWorkOrder(row.id, { actualQuantity: row.planQuantity })
    ElMessage.success('工单完成成功')
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleAdd = () => {
  // 创建工单逻辑
}

const handleEdit = (row) => {
  // 编辑工单逻辑
}

onMounted(() => {
  loadData()
})
</script>
